package org.fiel.admin.struts.actions;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.log4j.Logger;
import org.apache.struts.action.*;
import org.apache.struts.config.ActionConfig;
import org.apache.struts.upload.FormFile;
import org.fiel.admin.dao.InformacionDAO;
import org.fiel.admin.struts.actions.*;
import org.fiel.admin.struts.forms.InformacionForm;
import org.fiel.helpers.Enums;


public final class AddInformacionAction extends AdminAction{
    private Logger logger = Logger.getLogger(AddInformacionAction.class);
    
    public AddInformacionAction(){
    }

    public ActionForward execute( ActionMapping mapping
                                , ActionForm form
                                , HttpServletRequest request
                                , HttpServletResponse response )
    throws Exception{
        
        HttpSession session = request.getSession();
        ActionErrors errors = new ActionErrors();
        InformacionForm informacionForm = (InformacionForm)form;
        InformacionDAO iDAO = new InformacionDAO();
        
        try
        {
            if(!isAuthorized(request)){
                throw new Exception("Usuario no autorizado para esta operaci\363n.");
            }
            
            writeFiles(informacionForm);
            
            this.logger.debug("About to create information.");
            iDAO.createInformacion(informacionForm);
            this.logger.debug("Information created.");
        }
        catch(Exception ex)
        {
            this.logger.error("ERROR", ex);
            errors.add("org.apache.struts.action.GLOBAL_ERROR", new ActionError("error.exception"));
            errors.add("org.apache.struts.action.GLOBAL_ERROR", new ActionError("error.detail", ex.getMessage()));
        }
        
        if(mapping.getAttribute() != null)
            if("request".equals(mapping.getScope()))
                request.removeAttribute(mapping.getAttribute());
            else
                session.removeAttribute(mapping.getAttribute());
        if(!errors.isEmpty())
        {
            saveErrors(request, errors);
            return mapping.findForward("failed");
        } else
        {
            return mapping.findForward("success");
        }
    }

    public void writeFiles(InformacionForm informacionForm)
    throws Exception
    {
        this.logger.debug("writeFiles()");
        
        File file = null;
        FileOutputStream fos = null;
        String path = getServlet().getServletContext().getRealPath(Enums.getPath(Integer.parseInt(informacionForm.getIdentipo())));
        
        if (Integer.parseInt(informacionForm.getIdentipo())==Enums.TIPO_SECTORIALES.intValue())
        {
            path += "/" + this.getADHocPath(informacionForm.getFechaE());
            
            File directorio = new File(path);
            directorio.mkdirs();
        }
        
        this.logger.debug("about to write file...");
        
        try
        {
            if(informacionForm.getNameFile().getFileSize() > 0)
            {
                file = new File(path + File.separator + informacionForm.getNameFile().getFileName());
                fos = new FileOutputStream(file);
                fos.write(informacionForm.getNameFile().getFileData());
                fos.close();
            }
            if(informacionForm.getNameFileE().getFileSize() > 0)
            {
                file = new File(path + File.separator + informacionForm.getNameFileE().getFileName());
                fos = new FileOutputStream(file);
                fos.write(informacionForm.getNameFileE().getFileData());
                fos.close();
            }
            if(informacionForm.getImagen().getFileSize() > 0)
            {
                file = new File(path + File.separator + informacionForm.getImagen().getFileName());
                fos = new FileOutputStream(file);
                fos.write(informacionForm.getImagen().getFileData());
                fos.close();
            }
            this.logger.debug("File written.");
        }
        catch(Exception ex)
        {
            this.logger.error("ERROR", ex);
            throw new Exception(ex);
        }
    }
    
    public String getADHocPath(String fechaE)
    throws Exception
    {
        String meses[] = {
            "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", 
            "Noviembre", "Diciembre"
        };
        
        if(fechaE != null)
        {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date fecha = format.parse(fechaE);
        
            GregorianCalendar calendar = new GregorianCalendar();
            calendar.setTime(fecha);
            int mes = calendar.get(2);
            int anio = calendar.get(1);
            String path = meses[mes];
            path = path + Integer.toString(anio);
            return path;
        } 
        else
        {
            return "";
        }
    }
    
}